from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import logging

# 配置基础日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 初始化声明基类
Base = declarative_base()

# 导入配置
try:
    from config.settings import DATABASE_URL
except ImportError:
    # 如果无法导入配置，使用默认PostgreSQL连接
    DATABASE_URL = 'postgresql+psycopg2://postgres:postgres@localhost:5432/investment_data'
    logger.warning(f"无法导入数据库配置，使用默认连接: {DATABASE_URL}")

# 创建全局数据库引擎（优化连接池配置）
engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,
    pool_size=15,
    max_overflow=30,
    echo_pool=True
)

# 确保元数据初始化

try:
    Base.metadata.create_all(engine)
    logger.info("数据库表结构初始化成功")
except Exception as e:
    logger.error(f"数据库初始化失败: {e}")
    raise RuntimeError("数据库初始化失败") from e

def get_db_session():
    """创建并返回数据库会话（支持多线程）"""
    try:
        Session = sessionmaker(bind=engine)
        return Session()
    except Exception as e:
        logger.error(f"创建数据库会话失败: {e}")
        raise

# 导出需要外部访问的对象
__all__ = ['Base', 'engine', 'get_db_session']